import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../data/models/device_model.dart';
import '../../../data/providers/device_provider.dart';
import '../../../core/utils/logger.dart';
import '../../../constants/enums/device_type.dart';

/// 设备控制器 - 管理设备列表和设备操作
class DeviceController extends GetxController {
  final DeviceProvider _deviceProvider = Get.find<DeviceProvider>();
  
  // 设备列表
  final RxList<DeviceModel> devices = <DeviceModel>[].obs;
  
  // 设备详情
  final Rx<DeviceModel> selectedDevice = DeviceModel.empty().obs;
  
  // 加载状态
  final RxBool isLoading = false.obs;
  final RxBool isLoadingMore = false.obs;
  final RxBool hasMoreData = true.obs;
  
  // 列表过滤和分页
  final RxInt currentPage = 1.obs;
  final RxInt pageSize = 10.obs;
  final RxString searchQuery = ''.obs;
  final Rx<DeviceType?> selectedType = Rx<DeviceType?>(null);
  final RxString selectedStatus = ''.obs;
  final RxString sortField = ''.obs;
  final RxString sortOrder = 'desc'.obs;
  
  // 刷新控制器
  late RefreshController refreshController;
  
  // 搜索控制器
  late TextEditingController searchController;
  
  // 页面滚动控制器
  late ScrollController scrollController;
  
  @override
  void onInit() {
    super.onInit();
    refreshController = RefreshController();
    searchController = TextEditingController();
    scrollController = ScrollController();
    
    // 监听滚动加载更多
    scrollController.addListener(_onScroll);
    
    // 初始加载设备列表
    fetchDevices();
  }
  
  @override
  void onClose() {
    refreshController.dispose();
    searchController.dispose();
    scrollController.removeListener(_onScroll);
    scrollController.dispose();
    super.onClose();
  }
  
  /// 滚动监听 - 滚动到底部时加载更多
  void _onScroll() {
    if (scrollController.position.pixels >= scrollController.position.maxScrollExtent - 200 &&
        !isLoading.value &&
        !isLoadingMore.value &&
        hasMoreData.value) {
      loadMoreDevices();
    }
  }
  
  /// 获取设备列表
  Future<void> fetchDevices({bool showLoading = true}) async {
    if (showLoading) {
      isLoading.value = true;
    }
    
    currentPage.value = 1;
    hasMoreData.value = true;
    
    try {
      final response = await _deviceProvider.getDevices(
        page: currentPage.value,
        limit: pageSize.value,
        search: searchQuery.value.isNotEmpty ? searchQuery.value : null,
        type: selectedType.value,
        status: selectedStatus.value.isNotEmpty ? selectedStatus.value : null,
        sort: sortField.value.isNotEmpty ? sortField.value : null,
        order: sortOrder.value,
      );
      
      if (response.success && response.data != null) {
        devices.value = response.data!;
        
        // 检查是否有更多数据
        if (response.meta != null && response.meta!.containsKey('total')) {
          final int total = response.meta!['total'] as int;
          hasMoreData.value = devices.length < total;
        } else {
          hasMoreData.value = devices.length >= pageSize.value;
        }
        
        refreshController.refreshCompleted();
      } else {
        refreshController.refreshFailed();
        Get.snackbar(
          '加载失败',
          response.message ?? '获取设备列表失败',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    } catch (e) {
      refreshController.refreshFailed();
      LoggerUtil.e('获取设备列表异常', e);
      Get.snackbar(
        '加载失败',
        '获取设备列表出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 加载更多设备
  Future<void> loadMoreDevices() async {
    if (isLoadingMore.value || !hasMoreData.value) {
      return;
    }
    
    isLoadingMore.value = true;
    
    try {
      final nextPage = currentPage.value + 1;
      
      final response = await _deviceProvider.getDevices(
        page: nextPage,
        limit: pageSize.value,
        search: searchQuery.value.isNotEmpty ? searchQuery.value : null,
        type: selectedType.value,
        status: selectedStatus.value.isNotEmpty ? selectedStatus.value : null,
        sort: sortField.value.isNotEmpty ? sortField.value : null,
        order: sortOrder.value,
      );
      
      if (response.success && response.data != null) {
        // 如果返回的数据为空，则表示没有更多数据
        if (response.data!.isEmpty) {
          hasMoreData.value = false;
          refreshController.loadNoData();
          return;
        }
        
        // 更新页码
        currentPage.value = nextPage;
        
        // 添加新数据
        devices.addAll(response.data!);
        
        // 检查是否有更多数据
        if (response.meta != null && response.meta!.containsKey('total')) {
          final int total = response.meta!['total'] as int;
          hasMoreData.value = devices.length < total;
        } else {
          hasMoreData.value = response.data!.length >= pageSize.value;
        }
        
        refreshController.loadComplete();
      } else {
        refreshController.loadFailed();
        Get.snackbar(
          '加载失败',
          response.message ?? '获取更多设备失败',
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    } catch (e) {
      refreshController.loadFailed();
      LoggerUtil.e('加载更多设备异常', e);
      Get.snackbar(
        '加载失败',
        '获取更多设备出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoadingMore.value = false;
    }
  }
  
  /// 搜索设备
  void onSearch(String value) {
    searchQuery.value = value;
    fetchDevices();
  }
  
  /// 清除搜索
  void clearSearch() {
    searchController.clear();
    searchQuery.value = '';
    fetchDevices();
  }
  
  /// 切换设备类型筛选
  void setDeviceType(DeviceType? type) {
    selectedType.value = type;
    fetchDevices();
  }
  
  /// 切换设备状态筛选
  void setDeviceStatus(String status) {
    selectedStatus.value = status;
    fetchDevices();
  }
  
  /// 设置排序
  void setSorting(String field, {bool toggleOrder = true}) {
    // 如果是同一字段，切换排序顺序
    if (sortField.value == field && toggleOrder) {
      sortOrder.value = sortOrder.value == 'asc' ? 'desc' : 'asc';
    } else {
      sortField.value = field;
      // 默认为降序（最新在前）
      if (!toggleOrder) {
        sortOrder.value = 'desc';
      }
    }
    
    fetchDevices();
  }
  
  /// 获取设备详情
  Future<bool> fetchDeviceDetails(String deviceId) async {
    isLoading.value = true;
    
    try {
      final response = await _deviceProvider.getDeviceById(deviceId);
      
      if (response.success && response.data != null) {
        selectedDevice.value = response.data!;
        return true;
      } else {
        Get.snackbar(
          '加载失败',
          response.message ?? '获取设备详情失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      LoggerUtil.e('获取设备详情异常', e);
      Get.snackbar(
        '加载失败',
        '获取设备详情出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 添加设备
  Future<bool> addDevice(DeviceModel device) async {
    isLoading.value = true;
    
    try {
      final response = await _deviceProvider.addDevice(device);
      
      if (response.success && response.data != null) {
        // 添加到列表开头
        devices.insert(0, response.data!);
        
        Get.snackbar(
          '成功',
          '设备添加成功',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green.withOpacity(0.7),
          colorText: Colors.white,
        );
        
        return true;
      } else {
        Get.snackbar(
          '添加失败',
          response.message ?? '添加设备失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      LoggerUtil.e('添加设备异常', e);
      Get.snackbar(
        '添加失败',
        '添加设备出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 更新设备
  Future<bool> updateDevice(DeviceModel device) async {
    isLoading.value = true;
    
    try {
      final response = await _deviceProvider.updateDevice(device.id, device);
      
      if (response.success && response.data != null) {
        // 更新列表中的设备
        final index = devices.indexWhere((d) => d.id == device.id);
        if (index != -1) {
          devices[index] = response.data!;
        }
        
        // 如果是当前选中的设备，更新选中设备
        if (selectedDevice.value.id == device.id) {
          selectedDevice.value = response.data!;
        }
        
        Get.snackbar(
          '成功',
          '设备更新成功',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green.withOpacity(0.7),
          colorText: Colors.white,
        );
        
        return true;
      } else {
        Get.snackbar(
          '更新失败',
          response.message ?? '更新设备失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      LoggerUtil.e('更新设备异常', e);
      Get.snackbar(
        '更新失败',
        '更新设备出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 删除设备
  Future<bool> deleteDevice(String deviceId) async {
    isLoading.value = true;
    
    try {
      final response = await _deviceProvider.deleteDevice(deviceId);
      
      if (response.success && response.data == true) {
        // 从列表中移除
        devices.removeWhere((device) => device.id == deviceId);
        
        Get.snackbar(
          '成功',
          '设备删除成功',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green.withOpacity(0.7),
          colorText: Colors.white,
        );
        
        return true;
      } else {
        Get.snackbar(
          '删除失败',
          response.message ?? '删除设备失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      LoggerUtil.e('删除设备异常', e);
      Get.snackbar(
        '删除失败',
        '删除设备出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 控制设备
  Future<bool> controlDevice(String deviceId, String command, {Map<String, dynamic>? params}) async {
    isLoading.value = true;
    
    try {
      final response = await _deviceProvider.controlDevice(
        deviceId, 
        command,
        params: params,
      );
      
      if (response.success) {
        Get.snackbar(
          '成功',
          '设备控制命令发送成功',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green.withOpacity(0.7),
          colorText: Colors.white,
        );
        
        // 刷新设备详情
        await fetchDeviceDetails(deviceId);
        
        return true;
      } else {
        Get.snackbar(
          '控制失败',
          response.message ?? '设备控制命令发送失败',
          snackPosition: SnackPosition.BOTTOM,
        );
        return false;
      }
    } catch (e) {
      LoggerUtil.e('控制设备异常', e);
      Get.snackbar(
        '控制失败',
        '设备控制出错: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      return false;
    } finally {
      isLoading.value = false;
    }
  }
}

/// 刷新控制器 - 用于下拉刷新和上拉加载
class RefreshController {
  // 刷新完成回调
  void refreshCompleted() {}
  
  // 刷新失败回调
  void refreshFailed() {}
  
  // 加载完成回调
  void loadComplete() {}
  
  // 加载失败回调
  void loadFailed() {}
  
  // 没有更多数据回调
  void loadNoData() {}
  
  // 释放资源
  void dispose() {}
} 